﻿define(function (require, exports, module) {
    var Canvas = require('util/canvas');
    var Request = require('util/request');
    var IBirthplace = require('newRole/iBirthplace');

    var m_backCallback;
    var m_failureCallback;
    var m_mapId;
    var m_character

    exports.loadAsync = eval(Wind.compile('async', function (character) {
        m_character = character;

        $await(IBirthplace.renderAsync());

        Canvas.get('#back').on('click', m_backCallback);

        Canvas.get('.birthplace').on('click', function () {
            m_mapId = parseInt(this.getId());
        });

        Canvas.get('#ok').on('click', function () {
            m_okClickAsync().start();
        });

        Canvas.get('#failure').on('click', m_failureCallback);
    }));

    exports.setBackCallback = function (callback) {
        m_backCallback = callback;
    };

    exports.setFailureCallback = function (callback) {
        m_failureCallback = callback;
    };

    function getCreatingImage() { return Canvas.get('#creating')[0]; }

    var m_okClickAsync = eval(Wind.compile('async', function () {
        getCreatingImage().show();
        var response = $await(Request.ajaxAsync({
            url: 'createRole.do', data: {
                role: $.toJSON(m_character.data),
                mapId: m_mapId
            }
        }));
        $await(Wind.Async.sleep(300));
        getCreatingImage().hide();
        if (response.success) {
            require('main').loadAsync(response.roleId).start();
        }
        else {
            Canvas.get('#failureGroup')[0].show();
        }
        getCreatingImage().getLayer().draw();
    }));
});